package session;

import config.Configuration;
import executor.DefaultExecutor;
import executor.Executor;
import mapper.MappedStatement;
import mapper.MapperRegistry;
import mapper.SqlCommandType;

import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession<T> implements SqlSession {

    static {
        System.out.println("DefaultSqlSession is loaded");
    }


    private Configuration configuration;
    private Executor executor;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new DefaultExecutor();
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public int update(String name, Object[] params) {
        int result = 0;
        MappedStatement mappedStatement = configuration.getMappedStatement(name);
        String sql = mappedStatement.getResource();
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        try {
          result =(Integer) executor.execute(sqlCommandType, sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }

    public int delete(String name, Object[] params) {
        return this.update(name,params);
    }

    public int insert(String name, Object[] params) {
        return this.update(name,params);
    }

    public <T> List<T> selectList(String name, Object[] params,Class<T> tClass) {
        List<T> result;
        MappedStatement mappedStatement = configuration.getMappedStatement(name);
        String sql = mappedStatement.getResource();
        try {
            result =(List)executor.executeSelect(sql, params,tClass);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;

    }

    public <T> T selectOne(String name, Object[] params,Class<T> tClass) {
       T result;
        MappedStatement mappedStatement = configuration.getMappedStatement(name);
        String sql = mappedStatement.getResource();
        try {
            result =executor.executeSelectOne(sql, params, tClass);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }
}
